package cn.aylog.controller;

import cn.aylog.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping("/login")
    public String login(@RequestBody User user) throws JsonProcessingException {
        LOG.info("login接收到的参数: " + user);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        ObjectMapper mapper = new ObjectMapper();
        Map<String,Object> retData = new HashMap<>();
        try {
            subject.login(token);
            retData.put("data", "登录成功");
            retData.put("success", true);
            LOG.info("登录成功");
        } catch (Exception e) {
            retData.put("data", "用户名或密码错误");
            retData.put("success", false);
            LOG.error("校验失败,信息:" + e.getMessage());
            e.printStackTrace();
        }
        return mapper.writeValueAsString(retData);
    }
}
